package data;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;


public class Option {
	private static final long MEGABYTE = 1024L * 1024L;
	
	public static long bytesToMegabytes(long bytes) {
		return bytes / MEGABYTE;
	}

	/**
	 * This function will override the existing file with same name
	 * @param fileName
	 * @param totalNbOfItem
	 * @param maxScale
	 */
	public static void generateFile(String fileName, int totalNbOfItem, int maxScale){

		String content = "";
		Random random = new Random();

		long start = System.currentTimeMillis();

		System.out.println("Begin generate file");

		for (int i = 0 ; i < totalNbOfItem; ++i){
			int n = random.nextInt(maxScale);
			content += n + "\n";
		}
		System.out.println("\tFinish generating --> Writing content to file");
		File file = new File("./" + fileName);

		try {
			file.createNewFile();
			FileWriter fw = new FileWriter(file.getAbsoluteFile());
			BufferedWriter bw = new BufferedWriter(fw);
			bw.write(content);
			bw.close();

			long end = System.currentTimeMillis();
			System.out.println("[" + fileName + "] generated successfull");
			System.out.println("Generating time: " + (end - start) + " ms");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("Fail to generate [" + fileName + "]");
		}

	}

	public static int[] readIntegerFromFile(String fileName, int totalItems){

		BufferedReader br = null;
		try {

			int[] res = new int[totalItems];
			String sCurrentLine;
//			System.out.println("Now loading [" + fileName + "]");
			br = new BufferedReader(new FileReader("./" + fileName));

			int i = 0;
			while ((sCurrentLine = br.readLine()) != null) {
				res[i] = Integer.parseInt(sCurrentLine);
				++i;
			}

//			System.out.println("Load [" + fileName + "] successfull");
//			System.out.println("----------------------------");
			return res;

		} catch (IOException e) {
			e.printStackTrace();
			System.out.println("Error while loading [" + fileName + "]");
			return null;
		} finally {
			try {
				if (br != null)
					br.close();
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
	}

}
